var express = require('express');
var router = express.Router();
var utils = require('../functions/utils');
var replaceProhibitedWords = require('../functions/replaceProhibitedWords');

router.post('/', function(req,res)
{
/*
	Input parameters 

	 *  	sessionId		인증을 위한 session
	 *		gifId			ID
	 *		gifState		상태 (1 : public , 2: private)
*/
	var sessionId = req.body.sessionId;			utils.checkParamValue('sessionId' , sessionId);
	var gifId = req.body.gifId;			utils.checkParamValue('gifId' , gifId);
	var contentState = req.body.contentState;		utils.checkParamValue('contentState' , contentState);

	//utils.callLog(req);

	//utils.sessionTraceLog(req);


	var async = require('async');
	async.waterfall([
		function(cb)
		{
			utils.getUserIdWithSessionId(sessionId , cb);
		}
		,function(userId , cb) {
			if(!userId)
			{
				var err = new Error('Invalid session ID : ' + sessionId);
				err.code = '522';
				throw err;
			}

			// 변경하니까 master
			global.master_db.connection.getConnection(function(err,connection)
			{
				if(err)
				{
					throw err;
				}

				var input_param = [userId , gifId , contentState];

				var sql = 'call api_changeGifState_1_0(? , ? , ? , @result); SELECT @result as result';

				var query = connection.query(sql, input_param , function (err, rows) 
				{
					connection.release();
					if(err)
					{
						throw err;
					}

					var ret = {};	 // 기본값은 성공

					console.log(rows[1][0].result);

					switch(rows[1][0].result)
					{
						case 201:
							ret.code = '201';
							break;
						case 200:
							ret.code = '200';
							break;
						case 523:
							var err = new Error('Invalid gifId : ' + gifId);
							err.code = '523';
							throw err;
							break;
						default:
							throw new Error();

					}


					res.json(ret);
					res.end();


				}); 

			}); // getConnection

			////////////////////////////////////////////////////////////////////////

		}
	]); //waterfall	

});

module.exports = router;